package com.owo.springboot.service.impl;

import com.baidu.aip.ocr.AipOcr;
import com.owo.springboot.dto.CarPlateResult;
import com.owo.springboot.service.CarPlateService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

@Service
public class BaiduCarPlateServiceImpl implements CarPlateService {

    @Value("${baidu.ocr.appId}")
    private String appId;

    @Value("${baidu.ocr.apiKey}")
    private String apiKey;

    @Value("${baidu.ocr.secretKey}")
    private String secretKey;

    @Override
    public CarPlateResult recognizePlate(MultipartFile image) throws IOException {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(appId, apiKey, secretKey);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        try {
            // 调用车牌识别接口
            byte[] fileBytes = image.getBytes();
            JSONObject response = client.plateLicense(fileBytes, new HashMap<>());

            // 解析识别结果
            if (response.has("words_result") &&!response.isNull("words_result")) {
                JSONObject resultObj = response.getJSONObject("words_result");
                String plateNumber = resultObj.optString("number", "");
                double confidence = resultObj.optDouble("confidence", 0);
                return new CarPlateResult(plateNumber, confidence, true, "识别成功", null);
            } else {
                return new CarPlateResult(null, 0, false, "未识别到车牌", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CarPlateResult(null, 0, false, "API调用失败: " + e.getMessage(), null);
        }
    }
}